import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../config/router_page_name.dart';
import '../../services/auth_service.dart';
import '../../services/user_service.dart';
import '../../models/user.dart';

class ProfileLogic extends GetxController {
  final AuthService _authService = AuthService();
  final UserService _userService = UserService();

  final username = ''.obs;
  final isAdmin = false.obs;
  final isLoading = true.obs;
  final age = 0.obs;
  final gender = ''.obs;
  final RxList<User> allUsers = <User>[].obs;

  @override
  void onInit() {
    super.onInit();
    loadUserInfo();
  }

  Future<void> loadUserInfo() async {
    isLoading.value = true;
    try {
      final currentUsername = await _authService.getCurrentUsername();
      username.value = currentUsername ?? '未登录';

      isAdmin.value = await _authService.isCurrentUserAdmin();

      // Load age and gender
      final currentAge = await _authService.getCurrentUserAge();
      if (currentAge != null) {
        age.value = currentAge;
      }

      final currentGender = await _authService.getCurrentUserGender();
      if (currentGender != null) {
        gender.value = currentGender;
      }

      if (isAdmin.value) {
        await loadAllUsers();
      }
    } catch (e) {
      SmartDialog.showToast('加载用户信息失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> loadAllUsers() async {
    try {
      final users = await _userService.getAllUsers();
      allUsers.value = users;
    } catch (e) {
      SmartDialog.showToast('加载用户列表失败: $e');
    }
  }

  Future<void> logout() async {
    try {
      await _authService.logout();
      Get.offAllNamed(RouterPageName.loginPage);
    } catch (e) {
      SmartDialog.showToast('退出登录失败: $e');
    }
  }
}
